<html>
<head>
    <title>断点续传</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/blueimp-md5/2.18.0/js/md5.min.js"></script>
    <style>
        .progress {
            width: 600px;
            height: 10px;
            border: 1px solid #ccc;
            border-radius: 10px;
            margin: 10px 0;
            overflow: hidden;
        }
        /* 初始状态设置进度条宽度为0px */
        .progress > div {
            width: 0;
            height: 100%;
            background-color: yellowgreen;
            transition: all .3s ease;
        }
    </style>
</head>
<body>
<input type="file" id="upload-file" />
<div class="progress">
    <div></div>
</div>
<button onclick="uploadFile()">上传</button>
</body>
<script>
    function uploadFile() {
        //获取上传的文件
        console.info($('#upload-file').get(0).files)
        var blob = $('#upload-file').get(0).files[0];
        console.info(md5(blob))
        return
        var start = 0;
        var end;
        var index = 0;
        var fileSize = blob.size;
        var fileName = blob.name;
        console.info(fileName, fileSize);

        //计算文件切片总数
        var bytesPerPiece = 1024 * 1024; // 每个文件切片大小定为1MB .
        var totalPieces = Math.ceil(fileSize / bytesPerPiece);

        console.info(totalPieces);
        while(start < fileSize) {
            end = start + bytesPerPiece;
            if (end > fileSize) {
                end = fileSize;
            }

            // 切割文件
            var chunk = blob.slice(start, end);
            console.info(chunk);
            var sliceName = blob.name + '_' + index;
            var formData = new FormData();

            formData.append("file", chunk, sliceName);

            $.ajax({
                url: '/file/upload',
                type: 'post',
                mineType: 'multipart/form-data',
                cache: false,
                processData: false,
                contentType: false,
                data: formData,
                // xhr: function() {
                //     var xhr = new XMLHttpRequest();
                //     //使用XMLHttpRequest.upload监听上传过程，注册progress事件，打印回调函数中的event事件
                //     xhr.upload.addEventListener('progress', function (e) {
                //         console.log(e);
                //         //loaded代表上传了多少
                //         //total代表总数为多少
                //         var progressRate = (e.loaded / e.total) * 100 + '%';
                //
                //         //通过设置进度条的宽度达到效果
                //         $('.progress > div').css('width', progressRate);
                //     });
                //
                //     return xhr;
                // }
            }).done(function (res) {

            });

            start = end;
            index++;

        }

    }
</script>
</html>